package uo.ri.peristence.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import alb.util.jdbc.Jdbc;
import uo.ri.conf.Conf;
import uo.ri.peristence.MecanicosGateway;

public class MecanicosGatewatImpl implements MecanicosGateway {

	private Connection connection;

	@Override
	public void setConnection(Connection con) {
		this.connection = con;
	}

	@Override
	public Map<String, Object> findById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Map<String, Object>> findAllMechanics() {
		List<Map<String, Object>> listado = new ArrayList<Map<String, Object>>();
		PreparedStatement pst = null;
		ResultSet rs = null;

		try {
			pst = connection.prepareStatement(Conf.get("SQL_FIND_ALL_MECHANICS"));

			rs = pst.executeQuery();

			while (rs.next()) {
				listado.add(load(rs));
			}
			
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			Jdbc.close(rs, pst);
		}
		return listado;
	}

	@Override
	public void update(Long id, String nombre, String apellidos) {
		// Procesar
		PreparedStatement pst = null;

		try {
			
			pst = connection.prepareStatement(Conf.get("SQL_UPDATE_MECHANIC"));
			pst.setString(1, nombre);
			pst.setString(2, apellidos);
			pst.setLong(3, id);
			
			pst.executeUpdate();
			
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		finally {
			Jdbc.close(pst);
		}

	}

	@Override
	public void save(String nombre, String apellidos) {
		PreparedStatement pst = null;
		try {
			pst = connection.prepareStatement(Conf.get("SQL_INSERT_MECHANIC"));
			pst.setString(1, nombre);
			pst.setString(2, apellidos);
			
			pst.executeUpdate();
			
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		finally {
			Jdbc.close(pst);
		}

	}

	@Override
	public void delete(Long id) {
		PreparedStatement pst = null;
		try {
			
			pst = connection.prepareStatement(Conf.get("SQL_DELETE_MECHANIC"));
			pst.setLong(1, id);
			
			pst.executeUpdate();
			
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		finally {
			Jdbc.close(pst);
		}
	}

	
	
	private Map<String,Object> load(ResultSet rs) throws SQLException {
		//Cargamos los datos de los mecánicos
		Map<String, Object> mecanico = new HashMap<String, Object>();
		mecanico.put("id", rs.getLong("id"));
		mecanico.put("nombre", rs.getString("nombre"));
		mecanico.put("apellidos", rs.getString("apellidos"));
		
		return mecanico;
	}

}
